<?php
if(!isset($_SESSION))session_start();
include "connect.php";
$act ="";
if (isset($_GET["act"]))
	$act = $_GET["act"];

   $madh =""; $sl = 1;
	if (isset($_GET["madh"]))
		$madh = $_GET['madh'];
	if (isset($_GET["sl"]))
		$sl = $_GET["sl"];
	if (isset($_SESSION["giohang"]))
		$giohang = $_SESSION["giohang"];
	else	$giohang= array();
	
	function them($madh, $sl, &$giohang)
	{
		if (isset($giohang[$madh]))
			$giohang[$madh] = $giohang[$madh]+ $sl;
		else
			$giohang[$madh] = $sl;
	}

  function capnhat($madh, $sl, &$giohang)
  {
	  $sl = floor($sl *1);
	  if ($sl<=0) unset($giohang[$madh])  ;
	  else
	  $giohang[$madh]= $sl;
		  
	}
  function hienthi($gh)
  {
	 ?>
     <table border="1"><tr><td>STT</td><td>Ma dh</td>
        <td>Tendh</td><td>Gia</td><td>SL</td><td>TT</td></tr>   
    	<?php
		$i=0; $tong=0;
		foreach($gh as $m =>$sl)
		{	$i++;
			$sql ="select * from dongho where madh='$m' ";
			$kq = mysql_query($sql);
			if (mysql_num_rows($kq)>0)
			{
				$r =mysql_fetch_array($kq);
				$t = $r["tendh"]; $g = $r['gia'];
				echo '<form action=giohang.php>';
				echo "<tr><td>$i</td><td>$m</td>";
				echo "<td>$t</td><td>$g</td>";
				$tt = $g*$sl;  $tong +=$tt;
				echo "<td><input type=text name=sl value='$sl'></td>";
				echo "<td>$tt</td>";
				echo "<td><input type=submit value=Update></td></tr>";
				echo "<input type=hidden name=madh value='$m'>";
				echo "<input type=hidden name=act value='update'>";
				echo "</form>";
			
			}
		}
		echo "<tr><td colspan=5>Tong so tien</td><td>$tong</td></tr>";
		echo "</table>";
	 }

?>

<?php
if ($act=='add')
  them($madh, $sl, $giohang);
if ($act=="update")
	capnhat($madh, $sl, $giohang);
 hienthi($giohang);
?>
<hr />
<a href=sanpham.php>Tiep tuc mua hang</a>&nbsp;
<a href=thongtinkhachhang.php>Thanh Toan</a>
</body>
</html>
<?php
	 $_SESSION['giohang'] = $giohang;
?>